package view;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import javax.swing.JComponent;

import model.Card;
import model.PlayerModel;
import controller.MetaDeckController;

@SuppressWarnings("serial")
public class HandComponent extends JComponent{
	private PlayerModel model; 
	Set<Card> selection;
	public HandComponent(PlayerModel model) {
		this.model = model;
		clearSelection();
	}
	public Dimension getPreferredSize() {
		return new Dimension(350, 125);
	}
	public Dimension getMaximumSize() {
		return new Dimension(350, 125);
	}

	public Set<Card> getSelection() {
		return selection;
	}
	public void clearSelection() {
		selection = new HashSet<Card>();
	}
	
	private int getCardIndexAt(int x, int y) {
		for(int i=model.getCards().size()-1; i>=0; i--) {
			int ax = 15+15*i;
			int ay = selection.contains(model.getCards().get(i))?5:15;
			int bx = ax+ImageLoader.IMAGE_WIDTH;
			int by = ay+ImageLoader.IMAGE_HEIGHT;
			if(ax<=x && x<bx && ay<=y && y<by) {
				return i;
			}
		}
		return -1;
	}
	
	/** Returns the card displayed at the given location in the component. */
	public Card getCardAt(int x, int y) {
		int index = getCardIndexAt(x, y);
		if(index==-1) return null;
		else return model.getCards().get(index);
	}
	
	/** Toggles selection of the card displayed at the given location in the component. */
	public void toggleCardAt(int x, int y) {
		Card card = getCardAt(x, y);
		if(card==null) return;
		if(selection.contains(card)) selection.remove(card);
		else selection.add(card);
		repaint();
	}
	
	public void paint(Graphics tg) {
		Graphics2D g = (Graphics2D)tg;
		
		//Color the background dark green
		g.setColor(new Color(0, 100, 0));
		g.fillRect(0, 0, getWidth(), getHeight());
		
		boolean isMe = model.getName()==MetaDeckController.getInstance().getMyName();
		
		ArrayList<Card> hand = model.getCards();
		int xpos = 15;
		int ypos = 25;
		for(Card card : hand) {
			ypos = selection.contains(card)?15:25;
			
			Image im = isMe?ImageLoader.loadImage(card):ImageLoader.loadImage("back");
			g.drawImage(im, xpos, ypos, null);
			xpos+=15;
		}
		
		if(!isMe && hand.size()>=5) {
			g.setColor(Color.BLACK);
			g.setFont(new Font("Courier", Font.BOLD, 35));
			g.drawString(""+hand.size(), xpos+ImageLoader.IMAGE_WIDTH/2-25, ypos+ImageLoader.IMAGE_HEIGHT/2+7);
		}
		g.setColor(MetaDeckController.getInstance().getPlayerColor(model.getName()));
		g.setFont(new Font("Arial", Font.BOLD, 15));
		g.drawString(model.getName(), 5, 13);
	}
}
